package com.example.demo.config

import com.example.demo.service.MessageReceiverHandler
import org.eclipse.paho.client.mqttv3.MqttConnectOptions
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.integration.annotation.ServiceActivator
import org.springframework.integration.channel.DirectChannel
import org.springframework.integration.core.MessageProducer
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory
import org.springframework.integration.mqtt.core.MqttPahoClientFactory
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter
import org.springframework.messaging.MessageChannel
import org.springframework.messaging.MessageHandler

@Configuration
class MqttConfig {

    @Value("\${spring.mqtt.username}")
     private val username: String? = null

     @Value("\${spring.mqtt.password}")
     private val password: String? = null

    @Value("\${spring.mqtt.url}")
    private lateinit var url: String

    @Value("\${spring.mqtt.producer.clientId}")
    private lateinit var producerClientId: String

    @Value("\${spring.mqtt.producer.defaultTopic}")
    private lateinit var producerDefaultTopic: String

    @Value("\${spring.mqtt.consumer.clientId}")
    private lateinit var consumerClientId: String

    @Value("\${spring.mqtt.consumer.deviceStatusTopic}")
    private lateinit var consumerDeviceStatusTopic: String

    @Value("\${spring.mqtt.timeout}")
    private lateinit var timeout: String

    @Value("\${spring.mqtt.keepalive}")
    private lateinit var keepalive: String

    @Autowired
    private lateinit var messageReceiverHandler: MessageReceiverHandler


//    private val logger = LoggerFactory.getLogger(MqttConfig::class.java)
//    private val logger = org.slf4j.LoggerFactory.getLogger(MqttConfig::class.java)
    /**
     * MQTT连接器选项
     *
     * @return [org.eclipse.paho.client.mqttv3.MqttConnectOptions]
     */
    // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，
    // 这里设置为true表示每次连接到服务器都以新的身份连接
    // 设置连接的用户名 千万不能重复，一旦重复就会出现 ，新连接就会出现挤掉同Ｉd的旧连接
    // 设置连接的密码
    // 设置超时时间 单位为秒
    // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送心跳判断客户端是否在线，但这个方法并没有重连的机制
    // 设置“遗嘱”消息的话题，若客户端与服务器之间的连接意外中断，服务器将发布客户端的“遗嘱”消息。
    val mqttConnectOptions: MqttConnectOptions
        @Bean
        get() {
            val options = MqttConnectOptions()
            options.isCleanSession = true
            options.userName = username
            options.password = password!!.toCharArray()
            options.serverURIs = arrayOf(url)
            options.connectionTimeout = timeout.toInt()
            options.keepAliveInterval = keepalive.toInt()
            options.setWill("/server/offline", WILL_DATA, 2, false)
            return options
        }


    /**
     * MQTT客户端
     *
     * @return [org.springframework.integration.mqtt.core.MqttPahoClientFactory]
     */
    @Bean
    fun mqttClientFactory(): MqttPahoClientFactory {
        val factory = DefaultMqttPahoClientFactory()
        factory.connectionOptions = mqttConnectOptions
        return factory
    }

    /**
     * MQTT信息通道（生产者）
     *
     * @return [org.springframework.messaging.MessageChannel]
     */
    @Bean(name = [CHANNEL_NAME_OUT])
    fun mqttOutboundChannel(): MessageChannel {
        return DirectChannel()
    }

    /**
     * MQTT消息处理器（生产者）
     *
     * @return [org.springframework.messaging.MessageHandler]
     */
    @Bean
    @ServiceActivator(inputChannel = CHANNEL_NAME_OUT)
    fun mqttOutbound(): MessageHandler {
        val messageHandler = MqttPahoMessageHandler(
                producerClientId,
                mqttClientFactory()
        )
        messageHandler.setAsync(true)
        messageHandler.setDefaultTopic(producerDefaultTopic)
        return messageHandler
    }

    /**
     * MQTT消息订阅绑定（消费者）
     *
     * @return [org.springframework.integration.core.MessageProducer]
     */
    @Bean
    fun inbound(): MessageProducer {
        // 可以同时消费（订阅）多个Topic
        val adapter = MqttPahoMessageDrivenChannelAdapter(
                consumerClientId, mqttClientFactory(),
                consumerDeviceStatusTopic
        )
        adapter.setCompletionTimeout(5000)
        adapter.setConverter(DefaultPahoMessageConverter())
        adapter.setQos(1)
        // 设置订阅通道
        adapter.outputChannel = mqttInboundChannel()
        return adapter
    }

    /**
     * MQTT信息通道（消费者）
     *
     * @return [org.springframework.messaging.MessageChannel]
     */
    @Bean(name = [CHANNEL_NAME_IN])
    fun mqttInboundChannel(): MessageChannel {
        return DirectChannel()
    }

    /**
     * MQTT消息处理器（消费者）
     * 自行实现messageHandler 即可接收到订阅路径发上来的消息
     * @return [org.springframework.messaging.MessageHandler]
     */
    @Bean
    @ServiceActivator(inputChannel = CHANNEL_NAME_IN)
    fun handler(): MessageHandler {
        return messageReceiverHandler
    }

    companion object {


        private val WILL_DATA: ByteArray = "offline".toByteArray()

        /**
         * 订阅的bean名称
         */
        const val CHANNEL_NAME_IN = "mqttInputChannel"
        /**
         * 发布的bean名称
         */
        const val CHANNEL_NAME_OUT = "mqttOutboundChannel"

    }
}